<?php

namespace app\admin\controller\jeek\shop;

use app\common\controller\Backend;
use app\common\model\Category;
use tencent\api\Im;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 * sku商品插件
 */
class Skugoods extends Backend
{
    /**
     * 模型
     *
     * @var [type]
     */
    protected $model = null;

    /**
     * 是否是关联查询
     *
     * @var bool
     */
    protected $relationSearch = true;

    /**
     * 快速搜索时执行查找的字段
     *
     * @var string
     */
    protected $searchFields = 'name';

    /**
     * 是否开启Validate验证
     *
     * @var bool
     */
    protected $modelValidate = true;

    /**
     * 是否开启模型场景验证
     *
     * @var bool
     */
    protected $modelSceneValidate = true;

    /**
     * 初始化方法
     *
     * @return void
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\jeek\shop\SkuGoods;
        $this->specModel = new \app\admin\model\jeek\shop\SkuSpec;
        $this->itemModel = new \app\admin\model\jeek\shop\SkuItem;
        $this->productModel = new \app\admin\model\jeek\shop\SkuProduct;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $row) {
                $row->category_name = implode("、", Category::where('id', 'in', $row->category_id)->column('name'));
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                print_r($params);
                exit;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $this->createSpecItem($this->model->id, $params); //新增规格商品
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);


                    // 删除原本的规格参数
                    $this->specModel->where('goods_id', $row->id)->delete();
                    $this->itemModel->where('goods_id', $row->id)->delete();
                    $this->productModel->where('goods_id', $row->id)->delete();

                    $this->createSpecItem($row->id, $params); //新增规格商品
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->getVueInitData($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 真实删除
     */
    public function destroy($ids = "")
    {
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $k => $v) {
                $count += $v->delete(true);
            }
            $this->model->where($pk, 'in', $ids);
            // 删除原本的规格参数
            $this->specModel->where('goods_id', 'in', $ids)->delete();
            $this->itemModel->where('goods_id', 'in', $ids)->delete();
            $this->productModel->where('goods_id', 'in', $ids)->delete();
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 商品规格写入
     * @param [type] $goodsId
     * @param [type] $row
     * @return void
     */
    public function createSpecItem($goodsId, $row)
    {
        try {
            $groups = json_decode($row['groups'], true);
            $skus = json_decode($row['skus'], true);
            $items = json_decode($row['items'], true);

            // 写入spec
            $spec = [];
            foreach ($groups as $k => $v) {
                if (!count($items[$k])) {
                    continue;
                }
                $spec[] = ['name' => $v, 'goods_id' => $goodsId];
            }
            $res = $this->specModel->saveAll($spec);

            // 写入item
            $item = [];
            foreach ($res as $k => $v) {
                foreach ($items[$k] as $kk => $vv) {
                    $item[] = [
                        'name' => $vv,
                        'spec_id' => $v['id'],
                        'goods_id' => $goodsId // 仅为了方便删除
                    ];
                }
            }
            $res = $this->itemModel->saveAll($item);

            // 写入规格商品
            $product = [];
            foreach ($skus as $k => $v) {
                $v['key'] = $this->getKey($res, $v['attr']);
                $v['goods_id'] = $goodsId;
                unset($v['attr']);
                $product[] = $v;
            }
            $this->productModel->saveAll($product);
        } catch (Exception $e) {
            throw new Exception('添加出错'); //让外部回滚
        }
    }

    /**
     * 为规格商品匹配key值
     *
     * @param [type] $ids
     * @param [type] $attr
     * @return void
     */
    public function getKey($ids, $attr)
    {
        $key = '';
        foreach ($attr as $v) {
            foreach ($ids as $k => $vv) {
                if ($vv->name === $v) {
                    $key .= '_' . $vv->id;
                }
            }
        }
        return ltrim($key, '_');
    }

    /**
     * 获取vue参数
     * @param [type] $ids
     * @return void
     */
    public function getVueInitData($ids)
    {
        // 规格
        $groups = [];
        $items = [];
        $specs = $this->specModel->with('skuItems')->where('goods_id', $ids)->select();
        $arr = collection($specs)->toArray();
        $itemKey = []; //商品使用
        foreach ($specs as $k => $v) {
            $groups[] = $v['name'];
            $i = [];
            foreach ($v['sku_items'] as $kk => $vv) {
                $i[] = $vv['name'];
                $itemKey[$vv['id']] = $vv['name'];
            }
            $items[] = $i;
        }
        // 商品
        $products = $this->productModel->where('goods_id', $ids)->select();
        $products = collection($products)->toArray();
        foreach ($products as $k => $v) {
            $keyArr = explode('_', $v['key']);
            $attr = [];
            foreach ($keyArr as $kk => $vv) {
                $attr[] = $itemKey[$vv];
            }
            unset($products[$k]['key'], $products[$k]['id']);
            $products[$k]['attr'] = $attr;
        }
        // 渲染到js
        $this->assignconfig("skus", ['groups' => $groups, 'items' => $items, 'products' => $products]);
    }


    /**
     * Account:审核状态接口
     * User: Ixiangang
     * Date: 2025/1/17
     * Time: 18:16
     */
    public function examine($ids = null)
    {
        if (!$this->request->isPost()) {
            return $this->view->fetch();
        }
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $type = $this->request->get("type");
            $list = $this->model::where('id', '=', $ids)->find();
            if (!$list) {
                $this->error(__('数据不存在'));
            }
            $params = $this->request->post("row/a");
            $goods = $this->model->get($ids);
            $tencent_account = "consultant".$goods->id;
            if (!$params) {
                # 审核通过
                $params['examine'] = 2;
                $params['tencent_account'] = $tencent_account;
                $im = new Im();
                $chk_add_im = $im->check_bind($tencent_account);
                if (empty($chk_add_im)) {
                    $im->account_import($tencent_account, $goods->name, cdnurl($goods->image,true));
                }
            } else {
                if (!$params['examine_opinion']) {
                    $this->error("拒绝理由不能为空");
                }
                $params['examine'] = 3;
            }
            Db::startTrans();
            try {
                $result = $this->model::where('id', '=', $ids)->update($params);
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success(__('成功'));
            } else {
                $this->error(__('失败'));
            }
        }
    }




}
